package comWorld.msg.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gjs.tools.utils.Utils;

import comWorld.msg.Message;
import comWorld.msg.MessageManage;
import comWorld.user.UserInfo;
import comWorld.user.UserUrls;
import comWorld.user.manage.UserInfoManage;

/**
 * Servlet implementation class MsgsPageInit
 */
@WebServlet("/admin/msgs")
public class MsgsPageInit extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MsgsPageInit() {
        super();
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String otherIdStr = request.getParameter("user");
		otherIdStr = otherIdStr == null ? "" : otherIdStr;
		if (otherIdStr.length() == 0 || !otherIdStr.matches("^\\d+$")) {
			UserUrls userUrls = (UserUrls) request.getAttribute("userUrls");
			response.sendRedirect(userUrls.getAdminInbox());
			return;
		}
		int otherId = Integer.valueOf(otherIdStr);
		UserInfo userInfo = (UserInfo) session.getAttribute("visitorInfo");
				
		UserInfo otherInfo = UserInfoManage.getUserInfo(otherId);
		request.setAttribute("otherName", otherInfo.getName());
		request.setAttribute("otherId", otherId);
		
		List<Message> msgs = MessageManage.getMsgs(userInfo.getId(), "msgs", otherId);
		request.setAttribute("totalMsgs", msgs.size());
		
		int[] be = Utils.paging(request, 10, msgs.size());
		
		request.setAttribute("msgs", msgs.subList(be[0], be[1]));
		request.getRequestDispatcher("/msg/msgs.jsp").forward(request, response);
	}

}
